<template>
  <div
    class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
  >
    <div
      class="bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden"
    >
      <!-- 模态框头部  -->
      <div
        class="flex justify-between items-center p-6 border-b border-gray-200"
      >
        <h2 class="text-xl font-semibold text-gray-800">创建自定义题库</h2>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600 transition-colors"
        >
          <svg
            class="w-6 h-6"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            ></path>
          </svg>
        </button>
      </div>

      <!-- 模态框内容 -->
      <div class="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
        <form @submit.prevent="createWordBank">
          <!-- 题库名称 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              题库名称 <span class="text-red-500">*</span>
            </label>
            <input
              v-model="formData.name"
              type="text"
              placeholder="请输入题库名称"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>

          <!-- 词汇输入 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-700 mb-2">
              词汇列表 <span class="text-red-500">*</span>
            </label>
            <div class="mb-3">
              <div class="flex gap-2">
                <input
                  v-model="newWord"
                  type="text"
                  placeholder="输入词汇后按回车添加"
                  @keyup.enter="addWord"
                  class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <button
                  type="button"
                  @click="addWord"
                  :disabled="!newWord.trim()"
                  class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
                >
                  添加
                </button>
              </div>
            </div>

            <!-- 批量输入 -->
            <div class="mb-3">
              <button
                type="button"
                @click="showBatchInput = !showBatchInput"
                class="text-sm text-blue-600 hover:text-blue-800 transition-colors"
              >
                {{ showBatchInput ? "隐藏" : "显示" }}批量输入
              </button>
            </div>

            <div v-if="showBatchInput" class="mb-4">
              <textarea
                v-model="batchWords"
                placeholder="每行一个词汇，或用逗号分隔"
                rows="4"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
              ></textarea>
              <button
                type="button"
                @click="processBatchWords"
                class="mt-2 px-3 py-1 bg-green-500 text-white rounded text-sm hover:bg-green-600 transition-colors"
              >
                批量添加
              </button>
            </div>

            <!-- 词汇列表 -->
            <div
              class="border border-gray-200 rounded-lg p-3 min-h-[120px] max-h-60 overflow-y-auto"
            >
              <div
                v-if="formData.words.length === 0"
                class="text-gray-500 text-center py-8"
              >
                还没有添加词汇
              </div>
              <div v-else class="flex flex-wrap gap-2">
                <div
                  v-for="(word, index) in formData.words"
                  :key="index"
                  class="flex items-center gap-1 bg-blue-100 text-blue-800 px-2 py-1 rounded text-sm"
                >
                  <span>{{ word }}</span>
                  <button
                    type="button"
                    @click="removeWord(index)"
                    class="text-blue-600 hover:text-blue-800 ml-1"
                  >
                    ×
                  </button>
                </div>
              </div>
            </div>
            <div class="text-sm text-gray-600 mt-2">
              已添加 {{ formData.words.length }} 个词汇
            </div>
          </div>
        </form>
      </div>

      <!-- 模态框底部 -->
      <div class="flex justify-end gap-3 p-6 border-t border-gray-200">
        <button
          @click="$emit('close')"
          class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
        >
          取消
        </button>
        <button
          @click="createWordBank"
          :disabled="!canCreate || creating"
          class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors"
        >
          {{ creating ? "创建中..." : "创建题库" }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { apiService } from "../services/api";

const emit = defineEmits<{
  close: [];
  created: [];
}>();

const formData = ref({
  name: "",
  words: [] as string[],
});

const newWord = ref("");
const batchWords = ref("");
const showBatchInput = ref(false);
const creating = ref(false);

const canCreate = computed(() => {
  return formData.value.name.trim() && formData.value.words.length > 0;
});

// 添加单个词汇
const addWord = () => {
  const word = newWord.value.trim();
  if (word && !formData.value.words.includes(word)) {
    formData.value.words.push(word);
    newWord.value = "";
  }
};

// 移除词汇
const removeWord = (index: number) => {
  formData.value.words.splice(index, 1);
};

// 批量添加词汇
const processBatchWords = () => {
  const words = batchWords.value
    .split(/[,\n]/)
    .map((word) => word.trim())
    .filter((word) => word && !formData.value.words.includes(word));

  formData.value.words.push(...words);
  batchWords.value = "";
  showBatchInput.value = false;
};

// 创建题库
const createWordBank = async () => {
  if (!canCreate.value) return;

  creating.value = true;

  try {
    await apiService.createWordBank(formData.value.name, formData.value.words);
    emit("created");
  } catch (error) {
    console.error("创建题库失败:", error);
    alert(
      "创建题库失败: " + (error instanceof Error ? error.message : "未知错误")
    );
  } finally {
    creating.value = false;
  }
};
</script>
